package com.block.source.service.receive;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.RenYiHuaParam;
import com.block.source.model.api.XinXiaoRongParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class RenYiHuaReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)) {
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String requestNo = jsonObjectParamContent.getString("requestNo");
        JSONObject extObject = new JSONObject();
        extObject.put("requestNo",requestNo);
        sourceApiResult.setExtObject(extObject);
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(data);

        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        for (String key : jsonObject.keySet()) {
            if (StrUtil.isEmpty(jsonObject.getString(key))) {
                sourceApiResult.setReturnObject(this.getError(key + "撞库传入的信息有空值"));
                return sourceApiResult;
            }
        }
        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());
        userDataParam.setOutOrderNo(requestNo);
        userDataParam.setRealName("默认");


        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)) {
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String requestNo = jsonObjectParamContent.getString("requestNo");
        JSONObject extObject = new JSONObject();
        extObject.put("requestNo",requestNo);
        sourceApiResult.setExtObject(extObject);
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(data);


        JSONObject resultObject = JSON.parseObject(paramContentData);
        String orderId = resultObject.getString("orderId");
        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());


        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(),orderId);

        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();

        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject extObject = sourceApiParam.getExtObject();
        String requestNo = extObject.getString("requestNo");
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 0);
        returnObject.put("msg", "操作成功！");
        returnObject.put("requestNo", requestNo);

        JSONObject data = new JSONObject();
        data.put("orderId", requestNo);
        data.put("price", pushResultInfo.getPriceAmount());

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){

            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)) {
                data.put("logo", "");
            } else {
                data.put("logo", merchantBaseInfo.getCompanyLogo());
            }

            data.put("productName", thirdBaseInfo.getProductName());
            data.put("companyName", thirdBaseInfo.getCompanyName());

            if (CollUtil.isEmpty(thirdProtocolInfoList)){
                ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
                ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
                String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());

                data.put("protocolUrl", protocolUrl);
            }else{
                data.put("protocolUrl", thirdProtocolInfoList.get(0).getProtocolUrl());
            }
        }else{

            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)) {
                data.put("logo", "");
            } else {
                data.put("logo", merchantBaseInfo.getCompanyLogo());
            }

            data.put("productName", merchantBaseInfo.getInfoName());
            data.put("companyName", merchantBaseInfo.getInfoName());
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            data.put("protocolUrl", protocolUrl);
        }



        returnObject.put("data", data);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }



    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();


        JSONObject extObject = sourceApiParam.getExtObject();
        String requestNo = extObject.getString("requestNo");
        //{"data":{"remark":"进件完成","status":"000"},"respCode":"200","respMsg":"成功","success":true}

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()) {
            String status = data.getString("status");
            {
                if (StrUtil.equals(status, "000")) {
                    returnObject = this.getSuccess();
                    returnObject.put("requestNo",requestNo);
                    returnObject.put("data", null);
                    sourceApiResult.setReturnObject(returnObject);
                    return sourceApiResult;
                }
            }

        }

        returnObject = this.getError("推送失败");
        returnObject.put("data", null);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", 500);
        returnObject.put("msg", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "申请成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        RenYiHuaParam renYiHuaParam = JSON.parseObject(paramContent, RenYiHuaParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setMobileMd5(renYiHuaParam.getPhoneMd5());
        userDataParam.setMobile(renYiHuaParam.getPhone());
        userDataParam.setRealName(renYiHuaParam.getName());
        userDataParam.setAge(renYiHuaParam.getAge());
        userDataParam.setSex(renYiHuaParam.getSex() == 0 ? "2" : "1");
        userDataParam.setCityCode(renYiHuaParam.getCityCode());
        userDataParam.setUserIp(renYiHuaParam.getIp());


        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());

        String zhiMa = renYiHuaParam.getZhiMa().toString();
        if (StrUtil.equals(zhiMa, "1")) {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        } else if (StrUtil.equals(zhiMa, "2")) {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }else if (StrUtil.equals(zhiMa, "3")) {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else if (StrUtil.equals(zhiMa, "4")) {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }

        String GJJ = renYiHuaParam.getFund().toString();

        if (StrUtil.equals(GJJ, "1")) {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }
        String SheBao = renYiHuaParam.getSocial().toString();

        if (StrUtil.equals(SheBao, "1")) {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }
        String baodan = renYiHuaParam.getInsurance().toString();

        if (StrUtil.equals(baodan, "1")) {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }
        String house = renYiHuaParam.getHouse().toString();

        if (StrUtil.equals(house, "1")) {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }
        String car = renYiHuaParam.getCar().toString();

        if (StrUtil.equals(car, "1")) {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }

        String loan = renYiHuaParam.getLoanAmount();
        if (Integer.parseInt(loan) < 30000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (Integer.parseInt(loan) < 50000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (Integer.parseInt(loan) < 100000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (Integer.parseInt(loan) < 200000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        String professional = renYiHuaParam.getProfessional() != null ? renYiHuaParam.getProfessional().toString() : "99";
        if (StrUtil.equals(professional, "1")) {
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        } else if (StrUtil.equals(professional, "2")) {
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        } else if (StrUtil.equals(professional, "5")) {
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }else  {
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }

        userDataParam.setUserIp(renYiHuaParam.getIp());

        return userDataParam;
    }

}
